package ipad.asia.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import ipad.asia.entity.Consumer;
import ipad.asia.entity.Order;
import ipad.asia.entity.Product;
import ipad.asia.entity.SeckillProduct;
import ipad.asia.service.alipay.AlipayFeign;
import ipad.asia.service.consumer.ConsumerFeign;
import ipad.asia.service.order.OrderFeign;
import ipad.asia.service.product.ProductFeign;
import ipad.asia.service.seckill.SecKillFeign;
import ipad.asia.utils.MyTime;
import ipad.asia.utils.RandomNum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
public class PayController {
    @Autowired
    private OrderFeign orderFeign;
    @Autowired
    private ProductFeign productFeign;
    @Autowired
    private ConsumerFeign consumerFeign;
    @Autowired
    private MyTime myTime;
    @Autowired
    private RandomNum randomNum;
    @Autowired
    private SecKillFeign secKillFeign;
    @RequestMapping(value = "/pay/alipay")
    public ModelAndView alipay(
            HttpServletRequest request, Model model, HttpServletResponse response,
            @RequestParam(required = false,value = "productId")String productId,
            @RequestParam(required = false,value = "price")String price,
            @RequestParam(required = false,value = "inputOrderId")String inputOrderId,
            @RequestParam(required = false,value = "order_bbs")String order_bbs,
            @RequestParam(required = false,value = "newAddress")ArrayList newAddress
            ) throws UnsupportedEncodingException {

        System.out.println(newAddress);
//        return new ModelAndView("");
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        Product product=productFeign.getById(Integer.parseInt(productId));
        if(product.getNumber()<1){
            model.addAttribute("message","当前商品已售光！");
            return new ModelAndView("buy");
        }else {
            Consumer consumer1 = consumerFeign.getName((String) request.getSession().getAttribute("user"));
            List<Order> orders = orderFeign.findByConsumerId(consumer1.getId());
//            for (int i = 0; i < orders.size(); i++) {
//                if (orders.get(i).getStatues() == 0) {
//                    model.addAttribute("message", "你已有未付款的这款商品！");
//                    return new ModelAndView("redirect:/order/noPay");
//                }
//            }
            System.out.println("留言：" + order_bbs);
            HttpSession session = request.getSession();
            String user = (String) session.getAttribute("user");
            Consumer consumer = consumerFeign.getName(user);
            Product products = productFeign.getById(Integer.parseInt(productId));
            int rand1 = randomNum.RandomNumber1();
            int rand2 = randomNum.RandomNumber2();
            int rand3 = randomNum.RandomNumber2();
            String date = (String.valueOf(new SimpleDateFormat("ss").format(new Date())));
            //三次随机数加日期确保订单号不会重复！取日期数字过长不适用int，用long会有精度问题。
            String orderId = rand1 + rand2 + rand3 + date;
            System.out.println("orders--------" + orderId);
            System.out.println("user----" + user);
            System.out.println("products-----" + products);
            System.out.println("price----------" + price);
            System.out.println("productname-----" + products.getName());

            model.addAttribute("products", products);
            model.addAttribute("price", Integer.parseInt(price));
            model.addAttribute("consumer", consumer);
            System.out.println("地址：" + consumer.getAddress());
            System.out.println("时间" + myTime.LocalDateTime());


            List<String> orderIds = new ArrayList<>();

            for (int i = 0; i < orders.size(); i++) {
                if (orders.get(i).getStatues() != 0) {
                    orderIds.add(orders.get(i).getId() + "");
                }
            }
            System.out.println("除了未付款的orderid");
            if (orderIds.contains(inputOrderId)) {
                model.addAttribute("oderId", inputOrderId);
                return new ModelAndView("buy");
            } else {
                model.addAttribute("oderId", orderId);
                orderFeign.orderAdd(Integer.parseInt(orderId), consumer.getId(), Float.parseFloat(price), Integer.parseInt(productId),
                        1, order_bbs, products.getShopId(), consumer.getAddress(), 0, new Date(), null);
                //修改库存数量
                productFeign.updateNumber(product.getNumber() - 1, Integer.parseInt(productId));
                return new ModelAndView("redirect:http://49.235.177.225:1071/order/alipay?out_trade_no="+orderId+
                        "&subject="+product.getName()+"&total_amount="+price+"&body="+order_bbs);
            }
        }
    }


    @RequestMapping(value = "/pay/orderToAlipay")
    public ModelAndView orderToAlipay(
            HttpServletRequest request, Model model, HttpServletResponse response,
            @RequestParam(required = false,value = "productId")String productId,
            @RequestParam(required = false,value = "price")String price,
            @RequestParam(required = false,value = "orderId")String orderId,
            @RequestParam(required = false,value = "order_bbs")String order_bbs
    ) throws UnsupportedEncodingException {
        Product product = productFeign.getById(Integer.parseInt(productId));
        System.out.println("查询该商品是否正在优惠"+product.getHaveDiscount());
        if(product.getHaveDiscount()==1){
            SeckillProduct byId = secKillFeign.getById(Integer.valueOf(productId));
            System.out.println(byId);
            if(byId==null){
                return new ModelAndView("redirect:/order/all?sendMessage=失败，优惠过期！请取消订单重新购买！");
            }
        }

        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");
        return new ModelAndView("redirect:http://localhost:1091/order/alipay?out_trade_no="+orderId+
                        "&subject="+product.getName()+"&total_amount="+price+"&body="+order_bbs);
    }


    //返回给用户
     @RequestMapping(value = "/pay/return_url")
     public ModelAndView return_url(@RequestParam(value = "out_trade_no", required = false)String out_trade_no){
         System.out.println("订单号："+out_trade_no);
         orderFeign.updatePayStatue(Integer.parseInt(out_trade_no),1,new Date());
         return new ModelAndView("redirect:/order/all");
     }
     //返回给商家
    @RequestMapping(value = "/pay/notify_url")
    public String notify_url(
            @RequestParam(value = "out_trade_no", required = false) String out_trade_no,
            @RequestParam(value = "total_amount", required = false) String total_amount){
        System.out.println("这是回调的"+Integer.parseInt(out_trade_no));
        orderFeign.updatePayStatue(Integer.parseInt(out_trade_no),1,new Date());
        String result="订单号："+out_trade_no+",金额："+total_amount+"，状态："+"success";
        return JSON.toJSONString(result);
    }

}
